package com.example.shop_2305.detail

import androidx.lifecycle.viewModelScope
import com.example.lib_base.entity.AddCartEntity
import com.example.lib_base.entity.CommentEntity
import com.example.lib_base.entity.DetailEntity
import com.example.lib_base.entity.PreOrderEntity
import com.example.lib_base.entity.Res
import com.example.lib_base.mvvm.BaseViewModel
import com.example.lib_base.net.SingleLiveData
import com.example.lib_base.param.PPreOrder
import kotlinx.coroutines.launch

class DetailViewModel:BaseViewModel() {
    //请求商品详情
    val detailSuccess = SingleLiveData<Res<DetailEntity>>()
    val detailFail = SingleLiveData<String>()
    fun detail(id:Int,type:String){
        viewModelScope.launch {
            try {
                detailSuccess.postValue(apiService.detail(id, type))
            } catch (e: Exception) {
                detailFail.postValue(e.message.toString())
            }
        }
    }
    //添加到购物车
    val addSuccess = SingleLiveData<Res<AddCartEntity>>()
    val addFail = SingleLiveData<String>()
    fun addCart(cartNum:Int,productAttrUnique:String,productId:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["cartNum"] = cartNum
                map["productAttrUnique"] = productAttrUnique
                map["productId"] = productId
                addSuccess.postValue(apiService.addCart(mapToBody(map)))
            } catch (e: Exception) {
                addFail.postValue(e.message.toString())
            }
        }
    }
    //请求评论列表
    val commentSuccess = SingleLiveData<Res<CommentEntity>>()
    val commentFail = SingleLiveData<String>()
    fun comment(id:Int,limit:Int,page:Int,type:String){
        viewModelScope.launch {
            try {
                commentSuccess.postValue(apiService.comment(id, limit, page, type))
            } catch (e: Exception) {
                commentFail.postValue(e.message.toString())
            }
        }
    }

    //提交订单---预下单
    val preOrderSuccess = SingleLiveData<Res<PreOrderEntity>>()
    val preOrderFail = SingleLiveData<String>()
    fun preOrder(pPreOrder: PPreOrder){
        viewModelScope.launch {
            try {
                preOrderSuccess.postValue(apiService.preOrder(pPreOrder))
            } catch (e: Exception) {
                preOrderFail.postValue(e.message.toString())
            }
        }
    }
}